package com.guangfeng.yql.comm.netty.chatroom;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
public class ChatRoomMessageQueue {
    public static Map<String, LinkedBlockingQueue<String>> chatRoomQueueMap = new HashMap<>();

    public static void append(String chatRoomId, String message) {
        if (!chatRoomQueueMap.containsKey(chatRoomId)) {
            chatRoomQueueMap.put(chatRoomId, new LinkedBlockingQueue<String>(10));
        }
        LinkedBlockingQueue<String> queue = chatRoomQueueMap.get(chatRoomId);
        if (queue.remainingCapacity() == 0) {
            queue.poll();
        }
        try {
            queue.put(message);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static String[] getAll(String chatRoomId) {
        LinkedBlockingQueue<String> queue = chatRoomQueueMap.get(chatRoomId);
        if (queue == null) {
            return new String[0];
        }
        String[] array = queue.toArray(new String[0]);
        queue.clear();
        return array;
    }

}
